package sms

import (
	"net/http"
	"strconv"
	"strings"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"github.com/pkg/errors"
)

const (
	// AccessKeyID AccessKey ID
	accessKeyID = ""
	// AccessKeySecret AccessKey Secret
	accessKeySecret = ""
	smsParamTpl     = "{\"code\":\"{verifyCode}\"}"
	phoneLowLimit   = 100000
)

type SMSConfig struct {
	AK          string `json:"ak" yaml:"ak" mapstructure:"ak"`
	SK          string `json:"sk" yaml:"sk" mapstructure:"sk"`
	SMSParamTmp string `json:"sms_param_tmp" yaml:"sms_param_tmp" mapstructure:"sms_param_tmp"`
}

func SendVerifyCodeTo(phone string, code string) error {
	client, newClientErr := dysmsapi.NewClientWithAccessKey(
		"", accessKeyID, accessKeySecret,
	)
	if client == nil || newClientErr != nil {
		return errors.Wrap(newClientErr, "创建短信客户端失败")
	}
	request := dysmsapi.CreateSendSmsRequest()
	request.Scheme = "https"
	request.Domain = "dysmsapi.aliyuncs.com"
	request.PhoneNumbers = phone
	request.SignName = ""
	request.TemplateCode = ""
	request.TemplateParam = strings.Replace(smsParamTpl, "{verifyCode}", code, 1)

	response, sendErr := client.SendSms(request)
	if sendErr != nil {
		return errors.Wrap(sendErr, "发送短信失败")
	}
	if response == nil {
		return errors.New("发送短信失败，response响应失败")
	}
	if response.GetHttpStatus() != http.StatusOK {
		errMsg := "发送短信失败, code:" + strconv.Itoa(response.GetHttpStatus())
		return errors.New(errMsg)
	}
	return nil
}
